# -*- coding: utf-8 -*-
'''
	文件系统相关
'''

import math,os,hashlib,struct,shutil,glob

def globFiles(patterns, cwd = None):
	'''
		使用glob收集文件
	'''
	files = []
	for p in patterns:
		if cwd != None:
			p = cwd + '/' + p
		files.extend(glob.glob(p, recursive = True))
	return files

def formatFileSize(filesize, width = 8):
	'''
		格式化文件大小
	'''
	if filesize <= math.pow(1024,1):
		return ("%" + str(width) + "d B ") % filesize
	elif filesize <= math.pow(1024,2):
		return ("%" + str(width) + ".2f KB") % (filesize/math.pow(1024,1))
	elif filesize <= math.pow(1024,3):
		return ("%" + str(width) + ".2f MB") % (filesize/math.pow(1024,2))
	else:
		return ("%" + str(width) + ".2f GB") % (filesize/math.pow(1024,3))

def copyDirectory(srcPath, destPath):	
	'''
		复制目录
	'''
	for file in os.listdir(srcPath): 
		sourceFile = os.path.join(srcPath,  file) 
		targetFile = os.path.join(destPath,  file) 
		if os.path.isfile(sourceFile): 
			if not os.path.exists(destPath):  
				os.makedirs(destPath)  
			shutil.copyfile(sourceFile, targetFile)
		elif os.path.isdir(sourceFile): 
			copyDirectory(sourceFile, targetFile)

def clearDirectory(root):	
	'''
		清空目录
	'''
	if os.path.exists(root):
		for f in os.listdir(root):
			path = os.path.join(root, f)
			if os.path.isfile(path):
				os.remove(path)
			else:
				clearDirectory(path)
				os.rmdir(path)

def filterFiles(path, reserveReg = None, deleteReg = None):
	'''
		过滤目录
		@param reserveReg 保留正则表达式
		@param deleteReg 删除正则表达式
	'''
	files = globFiles('**/*', path)
	for f in files:
		if os.path.isfile(f):
			if reserveReg != None and reserveReg.match(f):
				continue
			if deleteReg != None and deleteReg.match(f):
				os.remove(f)

def buildPathTree(path, depth = 1, maxdepth = None):	
	''' 
		构建目录树 
	'''
	contents = []
	
	if depth == 1:
		path.rstrip("\\/")
		if os.path.isdir(path):
			path += "/"
		contents.append(path)
	files = [x for x in os.listdir(path)]
	for fidx in range(len(files)):
		file = files[fidx]
		if os.path.isdir(path + "/" + file):
			file += "/"
		if fidx == len(files) - 1:
			preline = "└─── "
		else:
			preline = "├─── "
		contents.append("\n" + "┆   "*(depth - 1))
		contents.append(preline + file)
		if file.endswith("/") and (not maxdepth or (depth < maxdepth)):
			contents.append(buildPathTree(path + "/" + file, depth + 1, maxdepth))
		
	return "".join(contents)

def getFileMD5(file, offest = 0, block_size=2**20):
	'''
	获得文件的MD5值
	'''
	md5 = hashlib.md5()
	with open(file,'rb') as cf:
		cf.seek(offest)
		while True:
			data = cf.read(block_size)
			if not data:
				break
			md5.update(data)
	md5 = struct.unpack("BBBBBBBBBBBBBBBB",md5.digest())
	return "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x" % \
		(md5[0],md5[1],md5[2],md5[3],md5[4],md5[5],md5[6],md5[7],md5[8],md5[9],md5[10],md5[11],md5[12],md5[13],md5[14],md5[15])


